import warnings
import shelve
import osconfeed

DB_NAME = 'data/schedule1_db'
CONFERENCE = 'conference.115'


class Record:
    def __init__(self, **kwargs):
        # 使用关键字参数传入的属性构建实例的常用简便方式
        self.__dict__.update(kwargs)


def load_db(db):
    raw_data = osconfeed.load()
    warnings.warn('loading ' + DB_NAME)
    for collection, rec_list in raw_data['Schedule'].items():
        record_type = collection[:-1]  # 把 'events' 变成 'event'
        for record in rec_list:
            key = '{}.{}'.format(record_type, record['serial'])
            record['serial'] = key
            db[key] = Record(**record)


if __name__ == '__main__':
    db = shelve.open(DB_NAME)
    # 判断数据库是否填充的简便方法是，检查某个已知的键是否存在；
    # 这里检查的键是 conference.115，即 conference 记录（只有一个）的键
    if CONFERENCE not in db:
        load_db(db)
    speaker = db['speaker.3471']
    print(type(speaker))
    print((speaker.name, speaker.twitter))
    db.close()
